export default class Socket {
  constructor(url) {
    this.websock = null
    // 固定的WebSocket地址：此处是从env文件中读取socket地址，可以自行从其他config文件中读取或直接写死
    // 如需使用动态WebSocket地址，请自行作ajax通讯后扩展
    this.ws_url = url
    // 开启标识
    this.socket_open = false
    // 心跳timer
    this.hearbeat_timer = null
    // 心跳发送频率
    this.hearbeat_interval = 1000

    // 是否自动重连
    this.is_reonnect = true
    // 重连次数
    this.reconnect_count = 3
    // 已发起重连次数
    this.reconnect_current = 1
    // 重连timer
    this.reconnect_timer = null
    // 重连频率
    this.reconnect_interval = 3000
  }

  init () {
    if (!('WebSocket' in window)) {
      return null
    }

    // 已经创建过连接不再重复创建
    // if (launchOrbitSocket.websock) {
    //   return launchOrbitSocket.websock
    // }

    this.websock = new WebSocket(this.ws_url)
    this.websock.onmessage = (e) => {
      this.receive(e)
    }
    // 关闭连接
    this.websock.onclose = () => {
      clearInterval(this.hearbeat_interval)
      this.socket_open = false
      // 需要重新连接
      if (this.is_reonnect) {
        this.reconnect_timer = setTimeout(() => {
          // 超过重连次数
          if (
            this.reconnect_current >
            this.reconnect_count
          ) {
            clearTimeout(this.reconnect_timer)
            return
          }

          // 记录重连次数
          this.reconnect_current++
          this.reconnect()
        }, this.reconnect_interval)
      }
    }
    this.websock.onopen = () => {
      this.socket_open = true
      this.is_reonnect = true
      // 开启心跳

    }
    // 连接发生错误
    this.websock.onerror = () => {
      return '错误'
    }
    return this.websock
  }

  receive (message) {
    return message
  }

  close () {
    clearInterval(this.hearbeat_interval)
    this.is_reonnect = false
    if (this.websock) {
      this.websock.close()
    }
  }

  reconnect () {
    if (this.websock && this.socket_open) {
      this.websock.close()
    }
    this.init()
  }
}